package com.yunxi.service.dubboService.impl.vip;

import com.github.pagehelper.PageInfo;
import com.yunxi.activiti.pojo.ActivitiResult;
import com.yunxi.activiti.pojo.ActivitiTaskVO;
import com.yunxi.activiti.pojo.ActivitiVO;
import com.yunxi.activiti.service.ActivitiManageDubboService;
import com.yunxi.bizToBaseData.service.SToSAttachDubboService;
import com.yunxi.core.base.Constant;
import com.yunxi.core.enums.DMSEnumsEntity;
import com.yunxi.core.util.StringUtil;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.LoginInfo;
import com.yunxi.core.web.ResponseUtil;
import com.yunxi.dealer.pojo.PartnerStorageVO;
import com.yunxi.dealer.service.PartnerDubboService;
import com.yunxi.dealer.service.PartnerStorageDubboService;
import com.yunxi.model.vip.StoVehicleExp;
import com.yunxi.model.vip.Vip;
import com.yunxi.model.vip.VipApply;
import com.yunxi.model.vip.VipApplyDetail;
import com.yunxi.order.pojo.OrderOemSaveReqVO;
import com.yunxi.order.pojo.PriceTryComputeRespVO;
import com.yunxi.order.service.OrderOemManagerDubboService;
import com.yunxi.service.localService.vip.StoVehicleExpService;
import com.yunxi.service.localService.vip.VipApplyDetailService;
import com.yunxi.service.localService.vip.VipApplyService;
import com.yunxi.service.localService.vip.VipService;
import com.yunxi.vehicle.service.VehiclePackageDubboService;
import com.yunxi.vip.pojo.StoVehicleExpVO;
import com.yunxi.vip.pojo.VipApplyDetailVO;
import com.yunxi.vip.pojo.VipApplyVO;
import com.yunxi.vip.pojo.VipVO;
import com.yunxi.vip.service.VipApplyDubboService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.parameters.P;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 * @author
 * @since 2019-09-06
 */
public class VipApplyDubboServiceImpl implements VipApplyDubboService {

    @Autowired
    @Qualifier(value = "vipApplyServiceImpl")
    VipApplyService vipApplyService;

    @Autowired
    @Qualifier(value = "vipApplyDetailServiceImpl")
    VipApplyDetailService vipApplyDetailService;

    @Autowired
    @Qualifier(value = "stoVehicleExpServiceImpl")
    StoVehicleExpService stoVehicleExpService;

    @Autowired
    ActivitiManageDubboService activitiManageDubboService;

    @Autowired
    OrderOemManagerDubboService orderOemManagerDubboService;

    @Autowired
    @Qualifier(value = "vipServiceImpl")
    VipService vipService;

    @Autowired
    SToSAttachDubboService sToSAttachDubboService;

    @Autowired
    TaskService taskService;

    @Autowired
    PartnerStorageDubboService partnerStorageDubboService;

    @Autowired
    VehiclePackageDubboService vehiclePackageDubboService;

    @Override
    public VipApplyVO getById(String id) throws InvocationTargetException, IllegalAccessException {
        VipApply vipApply = vipApplyService.getById(id);
        VipApplyVO vipApplyVO = new VipApplyVO();
        BeanUtils.copyProperties(vipApply, vipApplyVO);
        return vipApplyVO;
    }

    @Override
    public void saveOrUpdate(VipApplyVO vipApplyVO) throws InvocationTargetException, IllegalAccessException {
        VipApply vipApply = new VipApply();
        BeanUtils.copyProperties(vipApplyVO, vipApply);
        vipApplyService.saveOrUpdate(vipApply);
    }

    @Override
    public void removeById(String id) {
        vipApplyService.removeById(id);
    }

    @Override
    public PageInfo<VipApplyVO> findPageByVO(VipApplyVO vipApplyVO, Integer pageNum, Integer pageSize) throws InvocationTargetException, IllegalAccessException {
        PageInfo<VipApplyVO> pageInfo = vipApplyService.pageByVo(vipApplyVO, pageNum, pageSize);
        return pageInfo;
    }

    @Override
    public void removeByListVo(List<VipApplyVO> vipApplyVOList) throws IllegalAccessException, InvocationTargetException, InstantiationException {
        vipApplyService.removeByListVo(vipApplyVOList);
    }

    @Override
    public List listByVo(VipApplyVO vipApplyVO) {
        return vipApplyService.listByVo(vipApplyVO);
    }

    @Override
    @Transactional
    public ApiResult saveCas(VipApplyVO vipApplyVO, LoginInfo loginInfo) {
        VipApply va = new VipApply();

        Vip v = vipService.getById(vipApplyVO.getVipId());

        //拼装titile
        if(v==null){
            return ResponseUtil.fail(1000,"没有查询到客户信息");
        }else{
            vipApplyVO.setTitle(v.getProvinceName()+v.getCityName()+v.getRegionName()+v.getVipName()+vipApplyVO.getBusinessTypeCn());
        }

        if(StringUtils.isEmpty(vipApplyVO.getApplyNo())){
            vipApplyVO.setApplyNo("VO"+System.currentTimeMillis()+"");
        }

        if(StringUtils.isEmpty(vipApplyVO.getPartnerFinancial())
                &&StringUtils.isEmpty(vipApplyVO.getPartnerCode())
                &&StringUtils.isNotEmpty(v.getPartnerCode())){
            vipApplyVO.setPartnerCode(v.getPartnerCode());
        }
        if(vipApplyVO.getOp().equals("first")){
            if(StringUtils.isEmpty(loginInfo.getPartnerCode())){
                vipApplyVO.setSubmitType(1);
            }else{
                vipApplyVO.setSubmitType(0);
            }
        }

        BeanUtils.copyProperties(vipApplyVO,va);
        vipApplyService.saveOrUpdate(va);
        vipApplyVO.setApplyId(va.getApplyId());

        //保存附件表
        if (vipApplyVO.getAttachVOList() != null && vipApplyVO.getAttachVOList().size() > 0) {
            sToSAttachDubboService.saveByAttachVoList(vipApplyVO.getAttachVOList(), "vip_apply", va.getApplyId(), loginInfo);
        }

        List list = vipApplyVO.getListDetail();
        int acount=0;
        if(list!=null&&list.size()>0){
            for (int i=0;i<list.size();i++){
                VipApplyDetailVO  vdv = (VipApplyDetailVO)list.get(i);
                vdv.setApplyId(va.getApplyId());
                vdv.setCustomPackDetails(StringUtil.customPackCodeSort(vdv.getCustomPackDetails()));
                vdv.setPartnerCode(vipApplyVO.getPartnerCode());
                vdv.setPartnerFinancial(vipApplyVO.getPartnerFinancial());
                if(vdv.getVehiclePrice()==null) vdv.setVehiclePrice(new BigDecimal(0));
                VipApplyDetail vd = new VipApplyDetail();

                //查询型谱中文字符串
                if(StringUtils.isNotEmpty(vdv.getCustomPackDetails())){
                    String customPackNames = vehiclePackageDubboService.strByNodeCodeIn(StringUtil.customSqlStr(vdv.getCustomPackDetails()));
                    vdv.setCustomPackNames(customPackNames);
                }

                //价格试算
            /*
            vdv.setPriceTryCompute("8");
            PriceTryComputeRespVO priceVO = priceTryCompute(vdv);
            if(vdv.getVehiclePrice()!=null){
                if(vdv.getVehiclePrice().intValue()==0&&priceVO!=null){
                    vdv.setVehiclePrice(priceVO.getMarketPrice());
                    vdv.setSettlementPrice(priceVO.getSettlementPrice());
                    vdv.setPreferentialPrice(priceVO.getPreferentialPrice());
                    vdv.setTaxesPrice(priceVO.getTaxesPrice());
                }
            }
            */

                BeanUtils.copyProperties(vdv,vd);
                vipApplyDetailService.saveOrUpdate(vd);
                acount+=Integer.parseInt(vdv.getVehicleCount());

                //如果有上传附件信息，则保存
                if(vdv.getListVehicle()!=null&&vdv.getListVehicle().size()>0) {
                    for (int j = 0; j < vdv.getListVehicle().size(); j++) {
                        StoVehicleExpVO sve = vdv.getListVehicle().get(j);
                        StoVehicleExp sc = new StoVehicleExp();
                        BeanUtils.copyProperties(sve, sc);
                        stoVehicleExpService.saveOrUpdate(sc);
                    }
                }
            }
            va.setVcount(acount);
        }
        vipApplyService.saveOrUpdate(va);
        return ResponseUtil.ok(vipApplyVO);
    }

    public PriceTryComputeRespVO priceTryCompute(VipApplyDetailVO vad){
        //{"partnerCode":"D200113003","catalogCode":"AM861BFLCHL19B0","customPackCodes":""};
        OrderOemSaveReqVO vo = new OrderOemSaveReqVO();
        vo.setPartnerCode(vad.getPartnerCode());
        vo.setCatalogCode(vad.getVehicleCode());
        vo.setCustomPackCodes(vad.getCustomPackDetails());
        return orderOemManagerDubboService.priceTryCompute(vo);
    }

    @Override
    public void removeByVoId(VipApplyVO vipApplyVO) {
        VipApply va = new VipApply();
        BeanUtils.copyProperties(vipApplyVO,va);
        vipApplyService.removeById(va);
    }

    @Override
    @Transactional
    public ApiResult apply(VipApplyVO vipApplyVO ,LoginInfo loginInfo) {
        ApiResult ai = saveCas(vipApplyVO,loginInfo);
        vipApplyVO = (VipApplyVO)ai.getData();
        //启动流程
        //如果是渠道商则启动大客户渠道商流程
        ApiResult flowAr = null;
        if(StringUtils.isNotEmpty(loginInfo.getPartnerCode())){
            flowAr = activitiManageDubboService.start("dakehupartner",vipApplyVO.getApplyId(),loginInfo);
        }else{
            flowAr = activitiManageDubboService.start("dakehu",vipApplyVO.getApplyId(),loginInfo);
        }
        return flowAr;
    }

    @Override
    public PageInfo<VipApplyVO> pageWait(VipApplyVO vipApplyVO,Integer pageNum,Integer pageSize, LoginInfo loginInfo) {
        return vipApplyService.pageWait(vipApplyVO,pageNum,pageSize,loginInfo);
    }

    @Override
    @Transactional
    public void next(VipApplyVO vipApplyVO, LoginInfo loginInfo) {

        ActivitiVO avo = vipApplyVO.getActivitiVO();
        ActivitiTaskVO vo = activitiManageDubboService.getTaskByTaskId(avo.getTaskId());

        if(vo!=null){
            String taskName = vo.getTaskName();
            ApiResult ar = activitiManageDubboService.next(avo.getInstanceId(),avo.getTaskId(),avo.getTaskStatus(),loginInfo,avo.getRemark());

            ActivitiResult aar = (ActivitiResult)ar.getData();
            if(taskName!=null){
                if(taskName.equals("大客户经理")){
                    this.saveCas(vipApplyVO,loginInfo);
                }
                //判断流程是否结束
                if(aar.getActivitiStatus()== Constant.ACTIVITI_OVER){
                    if(avo.getTaskStatus().equals("AGREE")){
                        //订单转批售单及订货单
                        //封装批售单 ,生成订货单
                        vipApplyVO = vipApplyService.getByCas(vipApplyVO.getApplyId());
                        vipApplyVO.setStatus(DMSEnumsEntity.VipApplyStatus.AGREE.getCode());
                        createOem(vipApplyVO,loginInfo);
                    }else{
                        vipApplyVO.setStatus(DMSEnumsEntity.VipApplyStatus.REFUSE.getCode());
                    }
                    VipApply va = new VipApply();
                    BeanUtils.copyProperties(vipApplyVO,va);
                    vipApplyService.updateById(va);
                }
            }
        }else{
            ActivitiTaskVO hisvo = activitiManageDubboService.getHisTaskByTaskId(avo.getTaskId());
            if(hisvo!=null&&hisvo.getIsEnd()==1){
                if(avo.getTaskStatus().equals("AGREE")){
                    //订单转批售单及订货单
                    //封装批售单 ,生成订货单
                    vipApplyVO = vipApplyService.getByCas(vipApplyVO.getApplyId());
                    vipApplyVO.setStatus(DMSEnumsEntity.VipApplyStatus.AGREE.getCode());
                    createOem(vipApplyVO,loginInfo);
                }else{
                    vipApplyVO.setStatus(DMSEnumsEntity.VipApplyStatus.REFUSE.getCode());
                }
                VipApply va = new VipApply();
                BeanUtils.copyProperties(vipApplyVO,va);
                vipApplyService.updateById(va);
            }
        }
    }

    public void b2b(VipApplyVO vipApplyVO, LoginInfo loginInfo){
        vipApplyVO = vipApplyService.getByCas(vipApplyVO.getApplyId());
        createOem(vipApplyVO,loginInfo);
    }

    @Override
    public VipVO getVipByOrderCustomerNo(String orderCustomerNo) {
        return vipApplyService.getVipByOrderCustomerNo(orderCustomerNo);
    }

    @Override
    public void saveAttach(VipApplyVO vipApplyVO,LoginInfo loginInfo) {
        if (vipApplyVO.getAttachVOList() != null && vipApplyVO.getAttachVOList().size() > 0) {
            sToSAttachDubboService.saveByAttachVoList(vipApplyVO.getAttachVOList(), "vip_apply", vipApplyVO.getApplyId(), loginInfo);
        }
    }

    @Override
    public VipVO getByVin(String vin) {
        return vipService.getByVin(vin);
    }

    @Override
    public PageInfo<VipApplyVO> pageDone(VipApplyVO vipApplyVO, Integer pageNum, Integer pageSize, LoginInfo loginInfo) {
        return vipApplyService.pageDone(vipApplyVO,pageNum,pageSize,loginInfo);
    }

    @Override
    public void updateDiscount(VipApplyVO vipApplyVO) {
        vipApplyService.updateDiscount(vipApplyVO);
    }

    public void createOem(VipApplyVO vipApplyVO, LoginInfo loginInfo){
        //查询渠道商及收获地址

        //封装批售单
        List<VipApplyDetailVO> vdList = vipApplyVO.getListDetail();

        for (int i=0;i<vdList.size();i++){
            VipApplyDetailVO vvo = vdList.get(i);

            OrderOemSaveReqVO srv = new OrderOemSaveReqVO();

            srv.setPartnerCode(loginInfo.getPartnerCode());
            if(StringUtils.isNotEmpty(loginInfo.getPartnerCode())){
                srv.setOrderCreateType(1);
            }else{
                srv.setOrderCreateType(2);
            }

            srv.setCreateBy(loginInfo.getUserCode());
            srv.setUserCode(loginInfo.getUserCode());

            srv.setCatalogCode(vvo.getVehicleCode());
            srv.setColorCodeIn(vvo.getColorCodeIn());
            srv.setColorCodeOut(vvo.getColorCodeOut());
            srv.setNum(Integer.parseInt(vvo.getVehicleCount()));
            srv.setType("3");
            srv.setOrderType(1);
            //srv.set
            srv.setCustomPackCodes(vvo.getCustomPackDetails());

            BigDecimal marketPrice = vvo.getVehiclePrice().divide(new BigDecimal(vvo.getVehicleCount()));
            BigDecimal settlementPrice = new BigDecimal(0);
            BigDecimal preferentialPrice = new BigDecimal(0);
            BigDecimal taxesPrice = new BigDecimal(0);
            if(vvo.getSettlementPrice()!=null){
                settlementPrice = vvo.getSettlementPrice().divide(new BigDecimal(vvo.getVehicleCount()));
                preferentialPrice = vvo.getPreferentialPrice().divide(new BigDecimal(vvo.getVehicleCount()));
                taxesPrice = vvo.getTaxesPrice().divide(new BigDecimal(vvo.getVehicleCount()));
            }else{
                settlementPrice = (new BigDecimal(100).subtract(vipApplyVO.getDiscount())).multiply(marketPrice).divide(new BigDecimal(100));
                preferentialPrice = marketPrice.multiply(vipApplyVO.getDiscount()).divide(new BigDecimal(100));
            }

            srv.setMarketPrice(marketPrice);
            srv.setSettlementPrice(settlementPrice);
            srv.setPreferentialPrice(preferentialPrice); // 优惠金额
            srv.setTaxesPrice(taxesPrice);
            srv.setVipOrderId(vvo.getDetailId());//关联审批id
            srv.setDiscountProportion(vipApplyVO.getDiscount());
            srv.setSpecialDiscountProportion(vipApplyVO.getSpecialDiscount());
            srv.setPartnerCode(vvo.getPartnerCode());
            srv.setPartnerFinancial(vipApplyVO.getPartnerFinancial());


            if(vipApplyVO.getPayway()==null) vipApplyVO.setPayway(DMSEnumsEntity.PaywayType.CASH.getKey());
            srv.setPayway(vipApplyVO.getPayway());
            srv.setDetailId(vvo.getDetailId());
            srv.setVipId(vipApplyVO.getVipId());
            srv.setBusinessType(vipApplyVO.getBusinessType());
            srv.setSubmitType(vipApplyVO.getSubmitType());
            //根据渠道商查询发运地址默认获取第一个进行赋值

            //partnerDubboService.
            PartnerStorageVO psv = partnerStorageDubboService.getByPartnerVO(vvo.getPartnerCode());

            srv.setStorageCode(psv.getStorageCode());
            srv.setLinkman(psv.getLinkMan());
            srv.setLinkphone(psv.getLinkPhone());
            srv.setIsPickup("N");

            //封装订货单
            orderOemManagerDubboService.savePmsOrderOemExByVip(srv,loginInfo);
        }
    }

    @Override
    public VipApplyVO getByCas(String applyId) {
        return vipApplyService.getByCas(applyId);
    }

    @Override
    public ApiResult relateVehicle(String lsdh) {
        //需要判斷是否空閒的大客戶訂單
        //綁定完成需要調sap接口進行扣款


        //判斷渠道商是否有下架庫存進行綁定

        return null;
    }
}
